package cn.edu.scau.cmi.chenbingquan.client;

import cn.edu.scau.cmi.chenbingquan.multiton.Marshal;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;

// 多例用户类
public class MultitonClient extends Application {
	private Pane root = new Pane();
	private TextField tf;
	private Button button;
	private ListView<Text> lv;	// 文本显示列表
	
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) {
		
		root.setStyle("-fx-background-color: linear-gradient(to bottom right, ANTIQUEWHITE, CORNFLOWERBLUE)");
		
		tf = new TextField();
		tf.setPromptText("请输入元帅名称");
		tf.setFocusTraversable(false);
		tf.setLayoutX(60);
		tf.setLayoutY(70);
		
		button = new Button("创建");
		button.setLayoutX(260);
		button.setLayoutY(70);
		
		lv = new ListView<>();
		lv.getItems().add(new Text("元帅信息如下："));
		lv.setPrefSize(430, 280);
		lv.setFixedCellSize(25);
		lv.setLayoutX(60);
		lv.setLayoutY(150);
		root.getChildren().addAll(tf, button, lv);
		
		Scene scene = new Scene(root, 550, 450);
		stage.setScene(scene);
		stage.getIcons().add(new Image("cn/edu/scau/cmi/chenbingquan/image/窗口左上角图标.png"));
		stage.setTitle("多例模式");
		stage.setResizable(false);
		stage.show();
		
		// 事件
		button.setOnMouseClicked(e -> {
			if(tf.getText().equals("")) {		// 输入的元帅名字为空
				showBuildMessage("请先输入元帅名称");
			} else {
				if(Marshal.instances.size() < Marshal.TOTAL_AMOUNT && !Marshal.isNameExisted(tf.getText())) {
					Marshal.getInstances(tf.getText());			// 创建元帅
					int num = Marshal.instances.size();			// 获取元帅编号
					Text text = new Text("第" + num + "个" + Marshal.instances.get(num - 1).toString());
					text.setFill(Color.DODGERBLUE);
					lv.getItems().add(text);				// 添加文本
					showBuildMessage("元帅创建成功");
					
				} else if(Marshal.instances.size() < Marshal.TOTAL_AMOUNT){		// 元帅重名
					showBuildMessage("该元帅已经存在");
				} else {										// 元帅数量已经为10
					showBuildMessage("元帅只有10个");
				}
			}
			tf.setText("");
		});
	}
	
	// 显示关于创建信息的窗口
	public void showBuildMessage(String message) {
		
		VBox vBox = new VBox(60);
		vBox.setAlignment(Pos.CENTER);
		vBox.setStyle("-fx-background-color: ANTIQUEWHITE");
		
		Text text = new Text(message);
		text.setStyle("-fx-font-size: 25; -fx-fill: orange"); 
		
		Button button = new Button("确定");
		button.setPrefSize(60, 30);
		
		vBox.getChildren().addAll(text, button);
		
		Stage stage = new Stage();
		Scene scene = new Scene(vBox, 300, 250);
		stage.setScene(scene);
		stage.show();
		
		// 事件
		button.setOnMouseClicked(e -> stage.close() ); 		// 关闭窗口
	}
}
